package com.lib.image.preview;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import androidx.viewpager.widget.ViewPager;

import com.lib.image.R;
import com.lib.image.until.HeterotypicScreenUtils;
import com.lib.image.widget.ViewPagerFixed;
import com.providerlib.fileprovider.FileProvider7;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;

/**
 * 大图预览，再编辑
 * @author shalei
 */
public class PreviewPhotoActivity extends AppCompatActivity {

    private static final String KEY_POSITION = "key_position";
    private static final String KEY_IMAGE_LIST = "key_image_list";
    private static final String KEY_SHOW_EDIT = "key_show_edit";
    public static final String KEY_DELETE = "key_delete";
    private static final int REQUEST_CODE = 10001;
    private static final int REQUEST_CODE_CLIP = 10002;

    ViewPagerFixed mViewPager;
    ImageView btnBack;
    TextView mTextIndicator;
    LinearLayout stubIndicator;
    private View mTopToolBar;
    private View mBottomToolBar;
    private View mBtnDelete;

    private boolean mIsToolbarHide;
    private boolean mShowEdit;
    private int mCurrentPosition = 0;
    private ArrayList<String> imageList;


    protected ImagePageAdapter mAdapter;

    public static Intent newIntent(Activity activity, int position, ArrayList<String> imgList) {
        return newIntent(activity, position, imgList, false);
    }

    public static Intent newIntent(Activity activity, int position, ArrayList<String> imgList, boolean showEdit) {
        Intent intent = new Intent(activity, PreviewPhotoActivity.class);
        intent.putExtra(KEY_POSITION, position);
        intent.putExtra(KEY_IMAGE_LIST, imgList);
        intent.putExtra(KEY_SHOW_EDIT, showEdit);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        HeterotypicScreenUtils.openFullScreenModel(this);
        setContentView(R.layout.layout_preview_photo);
        initView();
        mCurrentPosition = getIntent().getIntExtra(KEY_POSITION, 0);
        imageList = getIntent().getStringArrayListExtra(KEY_IMAGE_LIST);
        if (imageList == null) {
            imageList = new ArrayList<>();
        }

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mCurrentPosition = position;
                mTextIndicator.setText((position + 1) + "/" + mAdapter.getCount());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mAdapter = new ImagePageAdapter(this, imageList);
        mAdapter.setPhotoViewClickListener((view, v, v1) -> onImageSingleTap());
        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(mCurrentPosition, false);
        mTextIndicator.setText(String.format("%d/%d", mCurrentPosition + 1, imageList.size()));
    }

    private void initView() {
        mViewPager = findViewById(R.id.viewpager);
        btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(this::onViewClicked);
        mTextIndicator = findViewById(R.id.text_indicator);
        stubIndicator = findViewById(R.id.stub_indicator);
        mTopToolBar = findViewById(R.id.top_toolbar);
        mBottomToolBar = findViewById(R.id.bottom_toolbar);
        mBtnDelete = findViewById(R.id.btn_delete);
        mShowEdit = getIntent().getBooleanExtra(KEY_SHOW_EDIT, false);
        if (mShowEdit) {
            stubIndicator.setVisibility(View.GONE);
            mBottomToolBar.setVisibility(View.VISIBLE);
            mBtnDelete.setVisibility(View.VISIBLE);
            findViewById(R.id.btn_edit).setOnClickListener(this::onViewClicked);
            findViewById(R.id.btn_replace).setOnClickListener(this::onViewClicked);
            findViewById(R.id.btn_delete).setOnClickListener(this::onViewClicked);
        } else {
            mBtnDelete.setVisibility(View.GONE);
            stubIndicator.setVisibility(View.VISIBLE);
            mBottomToolBar.setVisibility(View.GONE);
        }
    }

    private void onImageSingleTap() {
        if (mShowEdit) {
            showOrHideToolBar();
            return;
        }
        finish();
    }

    private void showOrHideToolBar() {
        if (mIsToolbarHide) {
            mTopToolBar.animate()
                    .setInterpolator(new FastOutSlowInInterpolator())
                    .translationYBy(mTopToolBar.getMeasuredHeight())
                    .start();
            mBottomToolBar.animate()
                    .translationYBy(-mBottomToolBar.getMeasuredHeight())
                    .setInterpolator(new FastOutSlowInInterpolator())
                    .start();
        } else {
            mTopToolBar.animate()
                    .setInterpolator(new FastOutSlowInInterpolator())
                    .translationYBy(-mTopToolBar.getMeasuredHeight())
                    .start();

            mBottomToolBar.animate()
                    .translationYBy(mBottomToolBar.getMeasuredHeight())
                    .start();
        }

        mIsToolbarHide = !mIsToolbarHide;
    }

    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.btn_replace) {
            openAlbum();
        } else if (id == R.id.btn_edit) {
            startActivityForResult(PhotoEditorActivity.newIntent(this, imageList.get(mCurrentPosition)), REQUEST_CODE_CLIP);
        } else if (id == R.id.btn_back) {
            finish();
        } else if (id == R.id.btn_delete) {
           showDeleteDialog();
        }
    }

    private void showDeleteDialog() {
        new AlertDialog
                .Builder(this)
                .setMessage("确认删除？")
                .setPositiveButton("取消", null)
                .setNegativeButton("确定", (dialog, which) -> {
                    Intent intent = new Intent();
                    intent.putExtra(KEY_DELETE, true);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }).show();
    }

    //重新选择图片
    private void openAlbum() {
        Matisse.from(this)
                .choose(MimeType.ofImage(), false)
                .countable(true)
                .capture(true)
                .captureStrategy(
                        new CaptureStrategy(true, FileProvider7.getFileProviderName(this), "test")
                )
                .maxSelectable(1)
                .gridExpectedSize((int) getResources().getDimension(R.dimen.preview_select_image2))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .showSingleMediaType(true)
                .originalEnable(false)
                .maxOriginalSize(10)
                .autoHideToolbarOnSingleTap(true)
                .forResult(REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) return;
        if (requestCode == REQUEST_CODE) {
            setResult(Activity.RESULT_OK, data);
            finish();
        } else if(requestCode == REQUEST_CODE_CLIP) {
            setResult(Activity.RESULT_OK, data);
            finish();
        }
    }
}
